/**
 * Project Name:cnsy-url-short-service
 * File Name:SpringContextUtils.java
 * Package Name:cn.cnsy123.shorturls.business.listener 
 * Date: 2020年4月14日-下午2:59:28
 * Copyright (c) 2020, yangpengfei@360@126.com All Rights Reserved. 
 *
 */

package cn.cnsy123.shorturls.business.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.cnsy123.shorturls.business.exception.BeanNotFoundException;

/**
 * ClassName: SpringContextUtils
 * 
 * @author yangpengfei
 * @date 2020年4月14日-下午2:59:28
 * @version 1.0
 * @since JDK 1.7
 */
public class SpringContextUtils implements ServletContextListener {
    
    private static final Logger logger = LoggerFactory.getLogger(SpringContextUtils.class);
    
    private static WebApplicationContext APPLICATION_CONTEXT = null;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        logger.info("初始化WebApplicationContext");
        APPLICATION_CONTEXT = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        APPLICATION_CONTEXT = null;
    }
    
    public static <T> T getBean(Class<T> requiredType) {
        if(requiredType == null) {
            throw new BeanNotFoundException("获取bean对象请求，类对象为空");
        }
        if(APPLICATION_CONTEXT == null) {
            throw new BeanNotFoundException("获取bean对象请求，WebApplicationContext为空");
        }
        T bean = APPLICATION_CONTEXT.getBean(requiredType);
        if(bean == null) {
            throw new BeanNotFoundException("获取bean对象请求，class:["+requiredType.getName()+"],不存在");
        }
        return bean;
    }

}
